package com.wanyangproject.fuwuactivity;


import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.wanyangproject.R;
import com.wanyangproject.activity.FaTieActivity;
import com.wanyangproject.entity.FuWuShenQingEntity;
import com.wanyangproject.entity.PhotoEntity;
import com.wanyangproject.entity.UserEntity;
import com.wanyangproject.entity.WuYeFuWuLieBiaoEntity;
import com.wanyangproject.entity.WuYeShiBaiEntity;
import com.wanyangproject.popuwindow.TakePhotoPopWin;
import com.wanyangproject.popuwindow.WuYeShenQingLeiXingPopupWindow;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.utils.GlideImageLoaderForPicker;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


// 物业服务界面
public class WuYeFuWuActivity extends AppCompatActivity {

    @BindView(R.id.image_back)
    ImageView imageBack;
    @BindView(R.id.image_shenqing_leixing)
    ImageView imageShenqingLeixing;
    @BindView(R.id.tv_neirong)
    TextView tvNeirong;
    @BindView(R.id.tv_shenqing_leixing)
    TextView tvShenqingLeixing;
    @BindView(R.id.tv_jianjie)
    TextView tvJianjie;
    @BindView(R.id.image_add_one)
    ImageView imageAddOne;
    @BindView(R.id.image_delete_one)
    ImageView imageDeleteOne;
    @BindView(R.id.image_add_two)
    ImageView imageAddTwo;
    @BindView(R.id.image_delete_two)
    ImageView imageDeleteTwo;
    @BindView(R.id.image_add_three)
    ImageView imageAddThree;
    @BindView(R.id.image_delete_three)
    ImageView imageDeleteThree;
    @BindView(R.id.tv_shenqing)
    TextView tvShenqing;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_miaoshu)
    EditText etMiaoshu;
    private WuYeShenQingLeiXingPopupWindow wuYeShenQingLeiXingPopupWindow;
    private TakePhotoPopWin takePhotoPopWin;
    private WuYeFuWuLieBiaoEntity wuYeFuWuLieBiaoEntity;
    private String lxid;
    private int ISOK = 0;
//    private ArrayList<ImageItem> list = new ArrayList<>();// 图片
    private ArrayList<String> list1 = new ArrayList<>();// 图片
    private ArrayList<ImageView> add = new ArrayList(); //  带加号的原图
    private ArrayList<String> imageUrl = new ArrayList<>(); // 图片网址
    private ArrayList<ImageView> shanchu = new ArrayList<>();// 删除的按钮
    private PhotoEntity photoEntity;
    private String leixingtitle;
    private ArrayList<String> list11 = new ArrayList<>();
    private ArrayList<String> list22 = new ArrayList<>();
    private Uri photoUri;
    private UserEntity userEntity;
    private FuWuShenQingEntity fuWuShenQingEntity;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wu_ye_fu_wu);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 21) {
            View dview = getWindow().getDecorView();
            dview.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }


//        物业服务列表的网络请求
        initWuYeFuWuLieBiaoHttp();

        add.add(imageAddOne);
        add.add(imageAddTwo);
        add.add(imageAddThree);

        shanchu.add(imageDeleteOne);
        shanchu.add(imageDeleteTwo);
        shanchu.add(imageDeleteThree);


        //        获取用户信息的网络请求
        initYongHuXinXiHttp();

    }












    //    获取用户信息的网络请求
    private void initYongHuXinXiHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "Life/user")
                .addHeader("token", ContractUtils.getTOKEN(WuYeFuWuActivity.this))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(WuYeFuWuActivity.this, response);
                        System.out.println(response + "    获取个人用户信息的网络请求");
                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            userEntity = gson.fromJson(response, UserEntity.class);
                            if (response.indexOf("200") != -1) {
//                                etName.setText(userEntity.getResponse().getNickname());//昵称
                                etName.setText(userEntity.getResponse().getRealname());//真实姓名
                                etPhone.setText(userEntity.getResponse().getUsername());
                            }
                        }
                    }
                });
    }









    //    物业服务列表的网络请求
    private void initWuYeFuWuLieBiaoHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "fuwu/index")
                .addHeader("token", ContractUtils.getTOKEN(WuYeFuWuActivity.this))
                .addParams("parkId", ContractUtils.getParkId(WuYeFuWuActivity.this))
                .addParams("typeId", "1")  //1:物业服务，2：企业服务
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e + "    物业服务eee");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response + "     物业服务的网络请求");
                        ContractUtils.Code500(WuYeFuWuActivity.this,response);
                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            wuYeFuWuLieBiaoEntity = gson.fromJson(response, WuYeFuWuLieBiaoEntity.class);
                            if (wuYeFuWuLieBiaoEntity.getResponse().getContent() == null) {

                            } else {
                                String content = wuYeFuWuLieBiaoEntity.getResponse().getContent();
                                String replace = content.replace("&nbsp;", " ");
                                tvJianjie.setText(replace);
                            }


                            for (int i = 0; i < wuYeFuWuLieBiaoEntity.getResponse().getData().size(); i++) {
                                list11.add(wuYeFuWuLieBiaoEntity.getResponse().getData().get(i).getId());
                                list22.add(wuYeFuWuLieBiaoEntity.getResponse().getData().get(i).getTitle());
                            }

//
//                            Object itemsOnClick = null;
//                            WuYeFuWuLieBiaoEntity.ResponseBean.leixing = wuYeFuWuLieBiaoEntity.getResponse().getData();
//                            wuYeShenQingLeiXingPopupWindow = new WuYeShenQingLeiXingPopupWindow(WuYeFuWuActivity.this, (View.OnClickListener) itemsOnClick);
                        }else if(response.indexOf("400") != -1){
                            ContractUtils.Code400(WuYeFuWuActivity.this,response);
                        }
                    }
                });
    }

    @OnClick({R.id.image_back, R.id.tv_shenqing, R.id.tv_shenqing_leixing, R.id.image_shenqing_leixing, R.id.image_add_one, R.id.image_delete_one, R.id.image_add_two, R.id.image_delete_two, R.id.image_add_three, R.id.image_delete_three})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.image_shenqing_leixing:
                break;
//            立即申请
            case R.id.tv_shenqing:
                if(tvNeirong.getText().toString().equals("")){
                    Toast.makeText(WuYeFuWuActivity.this, "请选择申请类型", Toast.LENGTH_SHORT).show();
                }else if(etMiaoshu.getText().toString().equals("")){
                    Toast.makeText(WuYeFuWuActivity.this, "请输入申请内容", Toast.LENGTH_SHORT).show();
                }else if(etName.getText().toString().equals("")){
                    Toast.makeText(WuYeFuWuActivity.this, "请输入姓名", Toast.LENGTH_SHORT).show();
                }else if(etPhone.getText().toString().equals("")){
                    Toast.makeText(WuYeFuWuActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                }else{
                    if(list1.size() == 0){
//                        没有图片的
                        initWuYeFuWuShenQingNoImageHttp();
                    }
                    for (int i = 0; i < list1.size(); i++) {
                        uploadFile(list1.get(i));
                    }
                }
                break;
//            申请类型
            case R.id.tv_shenqing_leixing:
                if(list22 == null || list11 == null){
                    return;
                }

                if(list22.size() == 0){
                    Toast.makeText(this, "暂无数据！", Toast.LENGTH_SHORT).show();
                    return;
                }


                OptionsPickerView pvOptions = new  OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3 ,View v) {
                        //返回的分别是三个级别的选中位置
                        String tx = list22.get(options1);
                        lxid = list11.get(options1);
                        tvNeirong.setText(tx);
                    }
                })
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .setTitleText("申请类型")//标题
                        .setSubCalSize(14)//确定和取消文字大小
                        .setTitleSize(16)//标题文字大小
                        .setTitleColor(Color.BLACK)//标题文字颜色
                        .setSubmitColor(Color.RED)//确定按钮文字颜色
                        .setLineSpacingMultiplier(3.0f)//设置两横线之间的间隔倍数
                        .setCancelColor(Color.parseColor("#AEAAAA"))//取消按钮文字颜色
                        .setTitleBgColor(Color.parseColor("#f5f5f5"))//标题背景颜色 Night mode
                        .setBgColor(Color.parseColor("#ffffff"))//滚轮背景颜色 Night mode
                        .setContentTextSize(16)//滚轮文字大小
                        .setLinkage(false)//设置是否联动，默认true
                        .setLabels("", "", "")//设置选择的三级单位
                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                        .setCyclic(false, false, false)//循环与否
                        .setSelectOptions(1, 1, 1)  //设置默认选中项
                        .setOutSideCancelable(false)//点击外部dismiss default true
                        .isDialog(false)//是否显示为对话框样式
                        .build();

                pvOptions.setPicker(list22);//添加数据源
                pvOptions.show();




//
//                wuYeShenQingLeiXingPopupWindow.showAtLocation(findViewById(R.id.wuye_fuwu), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//                wuYeShenQingLeiXingPopupWindow.setWuyefuwuClick(new WuYeShenQingLeiXingPopupWindow.WuYeFuWuClick() {
//                    @Override
//                    public void wuyefuwuClick(String title, String leixingid) {
//                        tvNeirong.setText(title);
//                        leixingtitle = title;
//                        lxid = leixingid;
//                    }
//                });
//
//




//                wuYeShenQingLeiXingPopupWindow.setWuyefuwuClick(new WuYeShenQingLeiXingPopupWindow.WuYeFuWuClick() {
//                    @Override
//                    public void wuyefuwuClick(String state) {
//                        tvNeirong.setText(state);
//                    }
//                });
                break;
            case R.id.image_add_one:
                ISOK = 0;
                //                弹出上传图片的弹窗
                initTanChu();
                break;
            case R.id.image_add_two:
                ISOK = 1;
                //                弹出上传图片的弹窗
                initTanChu();
                break;
            case R.id.image_add_three:
                ISOK = 2;
                //                弹出上传图片的弹窗
                initTanChu();
                break;
            case R.id.image_delete_one:
                list1.remove(0);
                TuPian();
                break;
            case R.id.image_delete_two:
                list1.remove(1);
                TuPian();
                break;
            case R.id.image_delete_three:
                list1.remove(2);
                TuPian();
                break;
        }
    }


    //    图片显示与隐藏
    private void TuPian() {

        for (int i = 0; i < add.size(); i++) {
            ImageView delete = shanchu.get(i);
            ImageView image = add.get(i);
            if (i <= list1.size() - 1) {
                image.setImageURI(Uri.parse(list1.get(i)));
            }
            if (i <= list1.size() - 1) {
                image.setVisibility(View.VISIBLE);
                delete.setVisibility(View.VISIBLE);
            } else if (i == list1.size()) {
                image.setVisibility(View.VISIBLE);
                delete.setVisibility(View.GONE);
                image.setImageResource(R.drawable.add);
            } else {
                image.setVisibility(View.GONE);
                delete.setVisibility(View.GONE);
            }
        }








//        for (int i = 0; i < add.size(); i++) {
//            ImageView delete = shanchu.get(i);
//            ImageView image = add.get(i);
//            if (i <= list.size() - 1) {
//                image.setImageURI(Uri.parse(list.get(i).path));
//            }
//            if (i <= list.size() - 1) {
//                image.setVisibility(View.VISIBLE);
//                delete.setVisibility(View.VISIBLE);
//            } else if (i == list.size()) {
//                image.setVisibility(View.VISIBLE);
//                delete.setVisibility(View.GONE);
//                image.setImageResource(R.drawable.add);
//            } else {
//                image.setVisibility(View.GONE);
//                delete.setVisibility(View.GONE);
//            }
//        }
    }

    //    弹出上传图片的弹窗
    private void initTanChu() {
        Object itemsOnClick = null;
        takePhotoPopWin = new TakePhotoPopWin(WuYeFuWuActivity.this, (View.OnClickListener) itemsOnClick);
        takePhotoPopWin.showAtLocation(findViewById(R.id.wuye_fuwu), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);




        //        点击相机

        takePhotoPopWin.setOnClickXiangji(new TakePhotoPopWin.OnClickXiangji() {
            @Override
            public void onClick(int id) {
//                        Intent open = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                        startActivityForResult(open,100);


                //                判断当前SDK版本号
                if (Build.VERSION.SDK_INT >= 23) {
//                    当前拨打电话权限是没有给的
                    if (ContextCompat.checkSelfPermission(WuYeFuWuActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//                        我要请求权限
                        ActivityCompat.requestPermissions(WuYeFuWuActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                    } else {
//                                SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//                                String filename = timeStampFormat.format(new Date());
//                                ContentValues values = new ContentValues(); //使用本地相册保存拍摄照片
//                                values.put(MediaStore.Images.Media.TITLE, filename);
//                                photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//
//                                // 设置 intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); photoUri = 保存图片得uri
//                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
//                                startActivityForResult(intent, 100);

                        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                            //创建文件夹 在本地文件Pictures 目录下创建 自己得文件夹
                            File dir = new File(Environment.getExternalStorageDirectory()+ "/Pictures/image");
                            if (!dir.exists()) {
                                dir.mkdirs();
                            }
                            //照片名称
                            File file = new File(dir, new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg");
                            photoUri = Uri.parse(file.getPath());

                            startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                                    .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)), 100);

                        } else {
//                                    showToast("请检查SDCard！");
                        }
                    }
                } else {
//                            SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//                            String filename = timeStampFormat.format(new Date());
//                            ContentValues values = new ContentValues(); //使用本地相册保存拍摄照片
//                            values.put(MediaStore.Images.Media.TITLE, filename);
//                            photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//
//                            // 设置 intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); photoUri = 保存图片得uri
//                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
//                            startActivityForResult(intent, 100);


                    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                        //创建文件夹 在本地文件Pictures 目录下创建 自己得文件夹
                        File dir = new File(Environment.getExternalStorageDirectory()+ "/Pictures/image");
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                        //照片名称
                        File file = new File(dir, new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg");
                        photoUri = Uri.parse(file.getPath());

                        startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                                .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)), 100);

                    } else {
//                                    showToast("请检查SDCard！");
                    }
                }




//
//                        SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//                        String filename = timeStampFormat.format(new Date());
//                        ContentValues values = new ContentValues(); //使用本地相册保存拍摄照片
//                        values.put(MediaStore.Images.Media.TITLE, filename);
//                        photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//
//                        // 设置 intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); photoUri = 保存图片得uri
//                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
//                        startActivityForResult(intent, 100);


//                        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {//判断是否有相机应用
//                            startActivityForResult(takePictureIntent, REQ_THUMB);
//
//                        }
            }
        });












        //                点击相册
        takePhotoPopWin.setOnClickXiangce(new TakePhotoPopWin.OnClickXiangce() {
            @Override
            public void onClick(int id) {
//                        Intent local = new Intent();
//                        local.setType("image/*");
//                        local.setAction(Intent.ACTION_GET_CONTENT);
//                        startActivityForResult(local, 2);

                ImagePicker imagePicker = ImagePicker.getInstance();
                imagePicker.setImageLoader(new GlideImageLoaderForPicker());   //设置图片加载器
                imagePicker.setShowCamera(true);  //显示拍照按钮
                imagePicker.setCrop(false);        //允许裁剪（单选才有效）
                imagePicker.setSaveRectangle(true);//是否按矩形区域保存
                imagePicker.setFocusHeight(169);
                imagePicker.setFocusWidth(169);
                imagePicker.setCrop(false);
                imagePicker.setSelectLimit(1);    //选中数量限制
                imagePicker.setOutPutX(800);//保存文件的宽度。单位像素
                imagePicker.setOutPutY(800);//保存文件的高度。单位像素

                Intent intent = new Intent(WuYeFuWuActivity.this, ImageGridActivity.class);
                startActivityForResult(intent, 1);

            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //        相机回调
        if (requestCode == 100) {
            String string = photoUri.toString();
            File file = new File(string);
            System.out.println(file.exists()+"      file");
            if(file.exists() == false){
                return;
            }

            if (list1.size() - 1 >= ISOK) {
                list1.set(ISOK, string);
            } else {
                list1.add(string);
            }
            TuPian();

        }








        if (data != null && requestCode == 1) {
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            if (images != null) {
                if (list1.size() - 1 >= ISOK) {
                    list1.set(ISOK, images.get(0).path);
                } else {
                    list1.add(images.get(0).path);
                }
                TuPian();


//                base转64
//                String path = images.get(0).path;
//                imageToBase64(path);
//                System.out.println(imageToBase64(path)+"   path");


            } else {
                Toast.makeText(this, "图片解析失败", Toast.LENGTH_SHORT).show();
            }
        }
//        else {
//            Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
//        }
    }


    //
    private void uploadFile(String imageItem) {
        final ProgressDialog progressDialog = new ProgressDialog(WuYeFuWuActivity.this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("请等待...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        File file = new File(imageItem);
        Luban.with(this)
                .load(file)
                .ignoreBy(100)
                //  .setTargetDir(AppConfig.DEFAULT_SAVE_IMAGE_PATH)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
//                        String url = ContractUtils.LOGIN_URL+"ceshi/ce_upload.html";
                        OkHttpClient okHttpClient = new OkHttpClient();
//                        RequestBody requestBody1 =new FormBody.Builder()
//                                .add("driverid",substring)
//                                .add("driver_img_type","1")
//                                .build();
                        RequestBody requestBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file))
                                .build();

                        Request request = new Request.Builder()
                                .url(ContractUtils.LOGIN_URL + "index/upload")
                                .post(requestBody)
                                .addHeader("token", ContractUtils.getTOKEN(WuYeFuWuActivity.this))
                                .build();

                        okHttpClient.newCall(request).enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
//                                        Toast.makeText(WuYeFuWuActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                progressDialog.dismiss();
                            }

                            @Override
                            public void onResponse(Call call, final Response response) throws IOException {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
//                                        Toast.makeText(PeopleInfoActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                                    }
                                });


                                progressDialog.dismiss();
                                String string = response.body().string();
                                Gson gson = new Gson();
                                photoEntity = gson.fromJson(string, PhotoEntity.class);
                                imageUrl.add(photoEntity.getResponse().getFileurl());
                                if (imageUrl.size() == list1.size()) {

//                                    物业服务申请的网络请求
                                        initWuYeFuWuShenQingHttp();
                                }
                                System.out.println(string + "   服务上传图片");
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }


    //    物业服务申请的网络请求
    private void initWuYeFuWuShenQingHttp() {

        String url = "";
        for (int i = 0; i < imageUrl.size(); i++) {
            url = url + imageUrl.get(i) + ",";
        }
        url = url.substring(0, url.length() - 1);
        System.out.println(url + "  urlurlurlurlurl ");

        if (lxid == null) {
            Toast.makeText(this, "请选择申请类型", Toast.LENGTH_SHORT).show();
            return;
        }

//        System.out.println(leixingtitle + "              leixingtitle");

        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "fuwu/shenqing")
                .addHeader("token", ContractUtils.getTOKEN(WuYeFuWuActivity.this))
                .addParams("image", url)
                .addParams("typeId", "1") //物业1  企业2
                .addParams("fuwuId", lxid)
                .addParams("content", etMiaoshu.getText().toString().trim())
                .addParams("name", etName.getText().toString().trim())
                .addParams("phone", etPhone.getText().toString().trim())
                .addParams("fuwuName", tvNeirong.getText().toString().trim())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e + "        服务申请的网络请求eee");

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(WuYeFuWuActivity.this,response);
                        System.out.println(response + "           服务申请的网络请求");
                        if(response.indexOf("200") != -1){
                            Gson gson = new Gson();
                            fuWuShenQingEntity = gson.fromJson(response, FuWuShenQingEntity.class);
                            Toast.makeText(WuYeFuWuActivity.this, "申请成功", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(WuYeFuWuActivity.this,FuWuShenQingJiLuJinXingActivity.class);
                            intent.putExtra("entype","3");
                            intent.putExtra("id",fuWuShenQingEntity.getResponse().getJiid());
                            startActivity(intent);
                            finish();
                        }else if(response.indexOf("400") != -1){
                            Gson gson = new Gson();
                            WuYeShiBaiEntity wuYeShiBaiEntity = gson.fromJson(response, WuYeShiBaiEntity.class);
                            Toast.makeText(WuYeFuWuActivity.this, wuYeShiBaiEntity.getMsg(), Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }
                });
    }






    //    物业服务申请的网络请求
    private void initWuYeFuWuShenQingNoImageHttp() {

//        String url = "";
//        for (int i = 0; i < imageUrl.size(); i++) {
//            url = url + imageUrl.get(i) + ",";
//        }
//        url = url.substring(0, url.length() - 1);
//        System.out.println(url + "  urlurlurlurlurl ");

        if (lxid == null) {
            Toast.makeText(this, "请选择申请类型", Toast.LENGTH_SHORT).show();
            return;
        }

//        System.out.println(leixingtitle + "              leixingtitle");

        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "fuwu/shenqing")
                .addHeader("token", ContractUtils.getTOKEN(WuYeFuWuActivity.this))
                .addParams("typeId", "1") //物业1  企业2
                .addParams("fuwuId", lxid)
                .addParams("content", etMiaoshu.getText().toString().trim())
                .addParams("name", etName.getText().toString().trim())
                .addParams("phone", etPhone.getText().toString().trim())
                .addParams("fuwuName", tvNeirong.getText().toString().trim())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e + "        服务申请的网络请求eee");

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(WuYeFuWuActivity.this,response);
                        System.out.println(response + "           服务申请的网络请求");

                        if(response.indexOf("200") != -1){
                            Gson gson = new Gson();
                            fuWuShenQingEntity = gson.fromJson(response, FuWuShenQingEntity.class);
                            Toast.makeText(WuYeFuWuActivity.this, "申请成功", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(WuYeFuWuActivity.this,FuWuShenQingJiLuJinXingActivity.class);
                            intent.putExtra("entype","3");
                            intent.putExtra("id",fuWuShenQingEntity.getResponse().getJiid());
                            startActivity(intent);
                            finish();
                        }else if(response.indexOf("400") != -1){
                            Gson gson = new Gson();
                            WuYeShiBaiEntity wuYeShiBaiEntity = gson.fromJson(response, WuYeShiBaiEntity.class);
                            Toast.makeText(WuYeFuWuActivity.this, wuYeShiBaiEntity.getMsg(), Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }
                });
    }




    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (permissions.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//                    String filename = timeStampFormat.format(new Date());
//                    ContentValues values = new ContentValues(); //使用本地相册保存拍摄照片
//                    values.put(MediaStore.Images.Media.TITLE, filename);
//                    photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//
//                    // 设置 intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); photoUri = 保存图片得uri
//                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
//                    startActivityForResult(intent, 100);

                    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                        //创建文件夹 在本地文件Pictures 目录下创建 自己得文件夹
                        File dir = new File(Environment.getExternalStorageDirectory()+ "/Pictures/image");
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                        //照片名称
                        File file = new File(dir, new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg");
                        photoUri = Uri.parse(file.getPath());

                        startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                                .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)), 100);

                    } else {
//                                    showToast("请检查SDCard！");
                    }
                } else {
//                    Toast.makeText(WoDeZiLiaoActivity.this, "", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
